package utilities.dbConnBase;

import java.sql.*;

import files.GetResourcesPath;

public class DBManager {
	private Connection connection;

	public DBManager(){
		connection = null;
	}

	public Connection getDBConnectionService() {
		if(connection == null)
			connect();
		return connection;
	}

	protected void connect(){
		try{
			
			message("Database connection starting...");
			uCanAccess();
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static void message(String s){
		System.out.println(s);
	}
	
	public String getPath(String fileName){
		String s = new GetResourcesPath().getPath(fileName);
		return s;
	}

	/**
	 * @
	 * pure java implementation to connect MS Access.
	 */
	private void uCanAccess(){

		try {
			String header="jdbc:ucanaccess://";
			//String url = "C:\\Users\\asl\\Desktop\\Roy\\workspace\\Comp433\\Comp433\\src\\DBAccess\\db.accdb;";
			String url = getPath("db.accdb");
			String setting = ";Memory=false";
			connection = DriverManager.getConnection(header + url + setting);
			
			message("Database Connection Established!");

		}
		catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Old method, need to use ODBC driver.
	 */
	private void jdbc_odbc(){
		//String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\DBAccess\\dbtest.accdb";
		System.out.println("preparing JdbcOdbcDriver");
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			String url = "jdbc:odbc:JDBC-ODBC-COMP433"; 
			message("JdbcOdbcDriver loaded");
			message("Geting connection to  database: JDBC-ODBC-COMP433");
			connection = DriverManager.getConnection(url);

			message("Database Connection Established!");

		}catch (Exception e) {
			e.printStackTrace();
		}
	}

}
